package com.example.notice

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.base.mvi.BaseActivity
import com.example.base.utils.WebSocketClient
import com.example.notice.databinding.ActivityNoticeBinding
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/notice/NoticeActivity")
@AndroidEntryPoint
class NoticeActivity : BaseActivity<ActivityNoticeBinding,NoticeIntent,NoticeViewModel>() {
    override fun getLayout(): Int  = R.layout.activity_notice

    override fun getVM(): Class<NoticeViewModel> = NoticeViewModel::class.java

    override fun initView() {
        WebSocketClient.start()
        binding.btnSend.setOnClickListener {
            WebSocketClient.sendMessage("集合通知|周三上午7:30教学楼前集合")
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
            WebSocketClient.mliveData.observe(this){
                //当it没有值时直接返回
                if(it.contains("|")) {
                    Log.d("sss", "initData:$it ")
                    //发送通知
                    val manager =
                        getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                    val channel =
                        NotificationChannel("id", "name", NotificationManager.IMPORTANCE_DEFAULT)
                    manager.createNotificationChannel(channel)
                    val split = it.split("|")
                    val intent = Intent(this,NoticeActivity::class.java)
                    val pendingIntent = PendingIntent.getActivity(
                        this,
                        100,
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                    val notification = Notification.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle(split[0])
                        .setContentText(split[1])
                        .setChannelId("id")
                        .setAutoCancel(true)//点击后自动消失
                        .setContentIntent(pendingIntent)//跳转到指定界面
                        .build()
                    manager.notify(1, notification)
                }else{
                    return@observe
                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        WebSocketClient.close()
    }

}